import { useTheme } from '@/contexts/ThemeContext';
import { applyPresetTheme, presetThemes, saveThemeConfig } from '@/utils/themeUtils';
import { SettingOutlined } from '@ant-design/icons';
import { Alert, Button, Card, ColorPicker, Divider, Form, Modal, Space, message } from 'antd';
import React, { useState } from 'react';

interface MenuColorConfigProps {
  onSuccess?: () => void;
}

const getThemeDisplayName = (themeName: keyof typeof presetThemes) => {
  const themeNames = {
    default: '默认主题',
    green: '绿色主题',
    purple: '紫色主题',
    orange: '橙色主题',
  };
  return themeNames[themeName] || themeName;
};

const MenuColorConfig: React.FC<MenuColorConfigProps> = ({ onSuccess }) => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm();
  const themeConfig = useTheme();

  const handleOpenModal = () => {
    form.setFieldsValue({
      colorPrimary: themeConfig.layout?.colorPrimary || '#FA541C',
      colorBgContainer: themeConfig.menu?.colorBgContainer || '#ffffff',
      colorText: themeConfig.menu?.colorText || '#000000d9',
      colorTextSecondary: themeConfig.menu?.colorTextSecondary || '#00000073',
      colorBgElevated: themeConfig.menu?.colorBgElevated || '#ffffff',
      colorBorder: themeConfig.menu?.colorBorder || '#f0f0f0',
    });
    setIsModalOpen(true);
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      const newThemeConfig = {
        ...themeConfig,
        layout: {
          ...themeConfig.layout,
          colorPrimary: values.colorPrimary,
        },
        menu: {
          ...themeConfig.menu,
          colorPrimary: values.colorPrimary,
          colorBgContainer: values.colorBgContainer,
          colorText: values.colorText,
          colorTextSecondary: values.colorTextSecondary,
          colorBgElevated: values.colorBgElevated,
          colorBorder: values.colorBorder,
        },
      };

      const success = saveThemeConfig(newThemeConfig);
      if (success) {
        message.success('主题配置保存成功');
        setIsModalOpen(false);
        onSuccess?.();
      } else {
        message.error('主题配置保存失败');
      }
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const handlePresetTheme = (themeName: keyof typeof presetThemes) => {
    const success = applyPresetTheme(themeName);
    if (success) {
      message.success(`已切换到${getThemeDisplayName(themeName)}主题`);
      onSuccess?.();
    } else {
      message.error('主题切换失败');
    }
  };

  return (
    <>
      <Button type="text" icon={<SettingOutlined />} onClick={handleOpenModal}>
        主题配置
      </Button>

      <Modal
        title="主题配置"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        width={800}
        okText="保存"
        cancelText="取消"
      >
        <Alert
          message="主题配置说明"
          description="配置的颜色将同时应用到顶部导航栏和左侧菜单，实现整体颜色统一。菜单旁边的黑线已被移除。"
          type="info"
          showIcon
          style={{ marginBottom: 16 }}
        />

        {/* 预设主题选择 */}
        <Card title="预设主题" size="small" style={{ marginBottom: 16 }}>
          <Space wrap>
            {Object.keys(presetThemes).map((themeName) => (
              <Button
                key={themeName}
                type={
                  themeConfig.layout?.title ===
                  presetThemes[themeName as keyof typeof presetThemes].layout?.title
                    ? 'primary'
                    : 'default'
                }
                onClick={() => handlePresetTheme(themeName as keyof typeof presetThemes)}
              >
                {getThemeDisplayName(themeName as keyof typeof presetThemes)}
              </Button>
            ))}
          </Space>
        </Card>

        <Divider>自定义主题颜色</Divider>

        <Form form={form} layout="vertical" style={{ marginTop: 16 }}>
          <Form.Item
            label="主色调（全局主题色）"
            name="colorPrimary"
            rules={[{ required: true, message: '请选择主色调' }]}
          >
            <ColorPicker format="hex" />
          </Form.Item>

          <Divider>菜单和顶部颜色</Divider>

          <Form.Item
            label="整体背景色（顶部+菜单）"
            name="colorBgContainer"
            rules={[{ required: true, message: '请选择整体背景色' }]}
          >
            <ColorPicker format="hex" />
          </Form.Item>

          <Form.Item
            label="文字颜色"
            name="colorText"
            rules={[{ required: true, message: '请选择文字颜色' }]}
          >
            <ColorPicker format="hex" />
          </Form.Item>

          <Form.Item
            label="次要文字颜色"
            name="colorTextSecondary"
            rules={[{ required: true, message: '请选择次要文字颜色' }]}
          >
            <ColorPicker format="hex" />
          </Form.Item>

          <Form.Item
            label="悬浮背景色"
            name="colorBgElevated"
            rules={[{ required: true, message: '请选择悬浮背景色' }]}
          >
            <ColorPicker format="hex" />
          </Form.Item>

          <Form.Item
            label="边框颜色"
            name="colorBorder"
            rules={[{ required: true, message: '请选择边框颜色' }]}
          >
            <ColorPicker format="hex" />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default MenuColorConfig;
